package com.kele.goods.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kele.model.goods.SearchGoods;
import com.kele.common.model.response.PageResult;
import com.kele.common.model.response.Result;
import com.kele.goods.mapper.GoodsImageMapper;
import com.kele.goods.mapper.GoodsMapper;
import com.kele.model.goods.Goods;
import com.kele.model.goods.GoodsImage;
import com.kele.model.goods.dto.GoodsDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Transactional//以下操作满足ACID，出现RuntimeException就会自动回滚
public class GoodsService {

    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    GoodsImageMapper goodsImageMapper;

    public Result insert(GoodsDTO goodsDTO){
        Goods goods = goodsDTO.getGoods();
        goods.setAuditStatus("0");//未提交
        goods.setCreateTime(new Date());
        goods.setUpdateTime(new Date());
        goods.setIsMarketable("0");
        goods.setIsDelete("0");

        System.out.println(goods.getId());
        goodsMapper.insert(goods);//
        System.out.println(goods.getId());

        /*int i = 10;
        int a = i / 0;*/
        List<GoodsImage> goodsImageList = goodsDTO.getGoodsImageList();
        for(GoodsImage goodsImage:goodsImageList){
            goodsImage.setGoodsId(goods.getId());
            goodsImage.setCreateTime(new Date());
            goodsImageMapper.insert(goodsImage);
        }
        return new Result(true,"1","新增商品成功");
    }

    public Result updateById(GoodsDTO goodsDTO){
        Goods goods = goodsDTO.getGoods();
        goodsMapper.updateById(goods);

        UpdateWrapper<GoodsImage> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(GoodsImage::getGoodsId,goods.getId());
        goodsImageMapper.delete(updateWrapper);//条件删除

        List<GoodsImage> goodsImageList = goodsDTO.getGoodsImageList();//前台修改后的
        for(GoodsImage goodsImage:goodsImageList){
            goodsImage.setGoodsId(goods.getId());
            goodsImage.setCreateTime(new Date());
            goodsImageMapper.insert(goodsImage);
        }
        return new Result(true,"1","修改商品成功");
    }

    public Result deleteById(Long id){
        goodsMapper.deleteById(id);

        UpdateWrapper<GoodsImage> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(GoodsImage::getGoodsId,id);
        goodsImageMapper.delete(updateWrapper);//条件删除

        return new Result(true,"1","删除商品成功");
    }

    public Result deleteBatchByIds(List<Long> ids){
        for (Long id : ids) {//iter
            deleteById(id);
        }
        return new Result(true,"1","删除商品成功");
    }

    public GoodsDTO selectById(Long id){
        Goods goods = goodsMapper.selectById(id);

        QueryWrapper<GoodsImage> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(GoodsImage::getGoodsId,id);
        List<GoodsImage> goodsImageList = goodsImageMapper.selectList(queryWrapper);

        GoodsDTO dto = new GoodsDTO();
        dto.setGoods(goods);
        dto.setGoodsImageList(goodsImageList);
        return dto;
    }

    /**
     *
     * @param pageNo
     * @param pageSize
     * @param searchMap
     * @return
     */
    public PageResult<Goods> findPage(Integer pageNo, Integer pageSize, Map searchMap){
        Page<Goods> page = new Page<>(pageNo,pageSize);

        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        String goodsName = (String)searchMap.get("goodsName");
        if(!StringUtils.isEmpty(goodsName)){
            queryWrapper.lambda().like(Goods::getGoodsName,goodsName);
        }
        String auditStatus = (String)searchMap.get("auditStatus");
        if(!StringUtils.isEmpty(auditStatus)){
            queryWrapper.lambda().eq(Goods::getAuditStatus,auditStatus);
        }
        String brandId = (String)searchMap.get("brandId");
        if(!StringUtils.isEmpty(brandId)){
            queryWrapper.lambda().eq(Goods::getBrandId,brandId);
        }
        String caption = (String)searchMap.get("caption");
        if(!StringUtils.isEmpty(caption)){
            queryWrapper.lambda().like(Goods::getCaption,caption);
        }
        String category1Id = (String)searchMap.get("category1Id");
        if(!StringUtils.isEmpty(category1Id)){
            queryWrapper.lambda().eq(Goods::getCategory1Id,category1Id);
        }
        String category2Id = (String)searchMap.get("category2Id");
        if(!StringUtils.isEmpty(category2Id)){
            queryWrapper.lambda().eq(Goods::getCategory2Id,category2Id);
        }
        String category3Id = (String)searchMap.get("category3Id");
        if(!StringUtils.isEmpty(category3Id)){
            queryWrapper.lambda().eq(Goods::getCategory3Id,category3Id);
        }
        queryWrapper.lambda().eq(Goods::getIsDelete,"0");

        String minPrice = (String)searchMap.get("minPrice");
        String maxPrice = (String)searchMap.get("maxPrice");
        Double price_min = 0D;
        Double price_max = 99999999D;
        if(!StringUtils.isEmpty(minPrice)){
            try {
                price_min = Double.parseDouble(minPrice);
                queryWrapper.lambda().gt(Goods::getPrice,price_min);
            }catch (NumberFormatException e){}
        }
        if(!StringUtils.isEmpty(maxPrice)){
            try {
                price_max = Double.parseDouble(maxPrice);
                queryWrapper.lambda().le(Goods::getPrice,price_max);
            }catch (NumberFormatException e){}
        }

        queryWrapper.lambda().orderByDesc(Goods::getUpdateTime);

        Page<Goods> page1 = goodsMapper.selectPage(page, queryWrapper);

        return new PageResult<>(page1.getTotal(),page1.getRecords());
    }

    public List<SearchGoods> findUpdatedAfter(Date lastSyncTime) {
        return goodsMapper.findUpdatedAfter(lastSyncTime);
    }
}
